/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package quanlinganhang.view;

import java.awt.Color;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.TableColumnModel;
import org.jdesktop.swingx.JXTableHeader;
import org.jdesktop.swingx.decorator.ColorHighlighter;
import org.jdesktop.swingx.decorator.HighlightPredicate;
import org.jdesktop.swingx.decorator.HighlighterFactory;
import quanlinganhang.dao.LoginDAO;
import quanlinganhang.dao.UserDAO;
import quanlinganhang.model.*;

/**
 *
 * @author phamduong
 */
public class ManageUser extends javax.swing.JPanel {

    MyTableScroller ts = null;
    UserTableModel model = null;

    /**
     * Creates new form ManageUser
     */
    public ManageUser() {
        try {
            model = new UserTableModel();
        } catch (SQLException ex) {
            Logger.getLogger(ManageUser.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(ManageUser.class.getName()).log(Level.SEVERE, null, ex);
        }
        initComponents();

        customizeTable();
        CountUsers();
    }

    /**
     * Đếm số lượng user và set ra label
     */
    private void CountUsers() {
        jlbCount.setText("" + jxTableUser.getRowCount());
    }

    /**
     * 
     */
    private void customizeTable() {
        jxTableUser.setModel(model);
        jxTableUser.setHighlighters(HighlighterFactory.createSimpleStriping());

        jxTableUser.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        //set màu sắc của row khi cuộn qua (màu background của row và màu text của row)
        jxTableUser.addHighlighter(new ColorHighlighter(HighlightPredicate.ROLLOVER_ROW,
                null, new Color(255, 102, 0)));
        //if did not choose 1 row, button Sửa and Xóa will be disable
        jxTableUser.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
            @Override
            public void valueChanged(ListSelectionEvent e) {
                if (jxTableUser.getSelectedRow() != -1) {
                    btEdit.setEnabled(true);
                    btDelete.setEnabled(true);
                } else {
                    btEdit.setEnabled(false);
                    btDelete.setEnabled(false);
                }
            }
        });
        TableColumnModel columnModel = jxTableUser.getColumnModel();
        jxTableUser.setTableHeader(new JXTableHeader(columnModel) {
            @Override
            public void updateUI() {
                super.updateUI();
                // need to do in updateUI to survive toggling of LAF 
                if (getDefaultRenderer() instanceof JLabel) {
                    ((JLabel) getDefaultRenderer()).setHorizontalAlignment(JLabel.CENTER);
                }
            }
        });
        jxTableUser.getColumn(0).setCellRenderer(new MyTableRenderer.IDRenderer());
        jxTableUser.getColumn(2).setCellRenderer(new MyTableRenderer.ColorRenderer());

//        filterController = new MyTableFilter(jxTableUser);
//        BindingGroup filterGroup = new BindingGroup();
//        filterGroup.addBinding(Bindings.createAutoBinding(READ,
//                txtSearch, BeanProperty.create("text"),
//                filterController, BeanProperty.create("filterString")));
//        filterGroup.bind();
    }

    public void reloadTable() {
        try {
            jxTableUser.setModel(new UserTableModel());
            //cột Mã người dùng có màu và căn giữa
            jxTableUser.getColumn(0).setCellRenderer(new MyTableRenderer.IDRenderer());
            //Cột  Mật khẩu đổi qua màu xanh
            jxTableUser.getColumn(2).setCellRenderer(new MyTableRenderer.ColorRenderer());
            CountUsers();
        } catch (SQLException | ClassNotFoundException ex) {
            new CustomMessageDialog(null, true, "Lỗi cơ sở dữ liệu",
                    "Có lỗi trong quá trình lấy thông tin dữ liệu", CustomMessageDialog.MESSAGE);
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jxTableUser = new org.jdesktop.swingx.JXTable();
        btAdd = new javax.swing.JButton();
        btEdit = new javax.swing.JButton();
        btDelete = new javax.swing.JButton();
        btUpdate = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jlbCount = new javax.swing.JLabel();
        jLabel12 = new javax.swing.JLabel();

        setBorder(javax.swing.BorderFactory.createEtchedBorder());

        jxTableUser.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jxTableUser.setToolTipText("Double click để sửa thông tin người dùng");
        jxTableUser.setColumnControlVisible(true);
        jScrollPane1.setViewportView(jxTableUser);

        btAdd.setIcon(new javax.swing.ImageIcon(getClass().getResource("/quanlinganhang/resources/add.png"))); // NOI18N
        btAdd.setText("Thêm");
        btAdd.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btAddActionPerformed(evt);
            }
        });

        btEdit.setIcon(new javax.swing.ImageIcon(getClass().getResource("/quanlinganhang/resources/edit.png"))); // NOI18N
        btEdit.setText("Sửa");
        btEdit.setEnabled(false);
        btEdit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btEditActionPerformed(evt);
            }
        });

        btDelete.setIcon(new javax.swing.ImageIcon(getClass().getResource("/quanlinganhang/resources/delete.png"))); // NOI18N
        btDelete.setText("Xóa");
        btDelete.setEnabled(false);
        btDelete.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btDeleteActionPerformed(evt);
            }
        });

        btUpdate.setIcon(new javax.swing.ImageIcon(getClass().getResource("/quanlinganhang/resources/refresh.png"))); // NOI18N
        btUpdate.setText("Cập nhật");
        btUpdate.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btUpdateActionPerformed(evt);
            }
        });

        jLabel1.setText("Số lượng");

        jlbCount.setForeground(new java.awt.Color(255, 0, 51));
        jlbCount.setText("0");

        jLabel12.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N
        jLabel12.setForeground(new java.awt.Color(0, 102, 153));
        jLabel12.setText("Quản lí người dùng");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(43, 43, 43)
                .addComponent(btAdd)
                .addGap(51, 51, 51)
                .addComponent(btEdit)
                .addGap(58, 58, 58)
                .addComponent(btDelete)
                .addGap(61, 61, 61)
                .addComponent(btUpdate)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jlbCount)
                .addGap(55, 55, 55))
            .addGroup(layout.createSequentialGroup()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 741, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 4, Short.MAX_VALUE))
            .addGroup(layout.createSequentialGroup()
                .addGap(239, 239, 239)
                .addComponent(jLabel12, javax.swing.GroupLayout.PREFERRED_SIZE, 245, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel12)
                .addGap(31, 31, 31)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 298, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btAdd)
                    .addComponent(btEdit)
                    .addComponent(btDelete)
                    .addComponent(btUpdate)
                    .addComponent(jLabel1)
                    .addComponent(jlbCount))
                .addContainerGap(33, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void btAddActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btAddActionPerformed
        new AddUser(LoginDAO.frmMain, true);
        reloadTable();
    }//GEN-LAST:event_btAddActionPerformed

    private void btUpdateActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btUpdateActionPerformed
        // TODO add your handling code here:
        reloadTable();
    }//GEN-LAST:event_btUpdateActionPerformed

    /**
     * Xóa user
     *
     * @param evt
     */
    private void btDeleteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btDeleteActionPerformed
        // TODO add your handling code here:
        int t = JOptionPane.showConfirmDialog(null, "Bạn có chắc chắn muốn xóa người"
                + " dùng này", "Xác nhận", JOptionPane.YES_OPTION);
        if (t == JOptionPane.YES_OPTION) {
            int selected = jxTableUser.getSelectedRow();
            long id = Long.parseLong(jxTableUser.getValueAt(selected, 0).toString());
            try {
                if (UserDAO.DeleteUser(id)) {
                    new CustomMessageDialog(null, true, "Thành công",
                            "Xóa người dùng thành công!", CustomMessageDialog.MESSAGE);
                    reloadTable();
                }
            } catch (ClassNotFoundException ex) {
                new CustomMessageDialog(null, true, "Lỗi cơ sở dữ liệu",
                        "Có lỗi trong quá trình xóa người dùng", CustomMessageDialog.MESSAGE);
            } catch (SQLException ex) {
                new CustomMessageDialog(null, true, "Lỗi cơ sở dữ liệu",
                        "Có lỗi trong quá trình xóa người dùng", CustomMessageDialog.MESSAGE);
            }
        }
    }//GEN-LAST:event_btDeleteActionPerformed

    private void btEditActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btEditActionPerformed
        // TODO add your handling code here:
        int selected = jxTableUser.getSelectedRow();
        long id = Long.parseLong(jxTableUser.getValueAt(selected, 0).toString());
        String name = jxTableUser.getValueAt(selected, 1).toString();
        String pass = jxTableUser.getValueAt(selected, 2).toString();
        boolean isAdmin = Boolean.getBoolean(jxTableUser.getValueAt(selected, 3).toString());
        new AddUser(null, true, id, name, pass, isAdmin);
        //reload table data
        reloadTable();
    }//GEN-LAST:event_btEditActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btAdd;
    private javax.swing.JButton btDelete;
    private javax.swing.JButton btEdit;
    private javax.swing.JButton btUpdate;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel12;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel jlbCount;
    private org.jdesktop.swingx.JXTable jxTableUser;
    // End of variables declaration//GEN-END:variables
}
